import React from 'react'
import ReactDOM from 'react-dom'

import './index.css'

class App extends React.Component {
    // 初始化状态
  state = {
    comments: [
      { id: 1, name: 'jack', content: '沙发！！！' },
      { id: 2, name: 'rose', content: '板凳~' },
      { id: 3, name: 'tom', content: '楼主好人' }
    ],

    // 评论人
    userName: '',
    // 评论内容：
    userContent: ''
  }
  del = (idx) => {
    const comments = [...this.state.comments]
    comments.splice(idx,1)

    this.setState({comments})
  }

  renderList = () => {
    return <ul>{this.state.comments.map((item,idx) =>{
        return (<li key={item.id}><h3>评论人：{item.name}</h3>
            <p>评论内容：{item.content}</p>
            <button onClick={()=>this.del(idx)}>删除</button></li>)
    })}</ul>
  }

  renderEmpty = () => {
      return <div className="no-comment">暂无评论</div>
  }

  clear = () => {
    this.setState({comments: []})
  }
  hChange = (e) => {
      const {name, value} = e.target

      this.setState({
          [name]: value
      })
  }
  hAdd = () => {
    const {userName, userContent, comments} = this.state

    this.setState({
        userName: '',
        userContent: '',
        comments: [{id:Date.now(), name: userName, content: userContent}, ...comments]
    })
  }

  render() {
    return (
      <div className="app">
        <div>
          <input
            name="userName"
            onChange={this.hChange}
            className="user" type="text" placeholder="请输入评论人" />
          <br />
          <textarea
            name="userContent"
            onChange={this.hChange}
            className="content"
            cols="30"
            rows="10"
            placeholder="请输入评论内容"
          />
          <br />
          <button onClick={this.hAdd}>发表评论</button>
          <button onClick={this.clear}>清空评论</button>
        </div>
        
          { this.state.comments.length ? this.renderList() : this.renderEmpty()}
      </div>
    )
  }
}

// 渲染组件
ReactDOM.render(<App />, document.getElementById('root'))
